package com.clkj.tramcarlibrary.tram;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceListener;
import com.amap.api.trace.TraceLocation;
import com.amap.api.trace.TraceOverlay;
import com.clkj.tramcarlibrary.R;
import com.clkj.tramcarlibrary.adapter.RouteFragmentPagerAdapter;
import com.clkj.tramcarlibrary.constant.Constants;
import com.clkj.tramcarlibrary.constant.Session;
import com.clkj.tramcarlibrary.entity.StopDetail;
import com.clkj.tramcarlibrary.entity.StopsDistance;
import com.clkj.tramcarlibrary.entity.Tramcar;
import com.clkj.tramcarlibrary.fragment.stopDetail.StopDetailFragment;
import com.clkj.tramcarlibrary.fragment.toNanmen.ToNmFragment;
import com.clkj.tramcarlibrary.fragment.toTiyuguan.ToTygFragment;
import com.clkj.tramcarlibrary.http.HttpService;
import com.clkj.tramcarlibrary.overlay.DrivingRouteOverlay;
import com.clkj.tramcarlibrary.overlay.WalkRouteOverlay;
import com.clkj.tramcarlibrary.schedulers.SchedulerProvider;
import com.clkj.tramcarlibrary.service.GpsworkSetting;
import com.clkj.tramcarlibrary.service.NetworkSetting;
import com.clkj.tramcarlibrary.util.ToastUtil;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


//有轨电车界面
public class TramcarActivity extends AppCompatActivity implements View.OnClickListener,
        LocationSource, AMapLocationListener, TramcarContract.View, TraceListener, AMap.InfoWindowAdapter, ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, RouteSearch.OnRouteSearchListener {

    //属性控件
    private ImageView iv_back;
    private TextView rd_title;
    private MapView tramcar_map;
    private TextView tv_recent_stop;
    private TextView tv_route_look;

    private LinearLayout ly_route_search;
    private RadioGroup rg_direction;
    private RadioButton rb_to_nm, rb_to_tyc;
    private ViewPager vp_routes;

    private ProgressDialog progDialog;
    //地图及定位相关
    private AMap aMap;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;
    private OnLocationChangedListener mOnLocationChangeListener;
    //你的定位坐标
    private Double longtitude, latitude;
    private LatLonPoint userLatLonPoint;
    //地图覆盖物——绘制marker

    private UiSettings mUiSettings;//UiSettings对象,可管理常用标签
    //这个界面里面所有的marker
    private List<Marker> mMarkerList = new ArrayList<Marker>();
    private Marker mLocMarker;
    private List<Tramcar> mTramcarList = new ArrayList<>();
    //轨迹纠偏
    LBSTraceClient mTraceClient;
    private int mSequenceLineID = 1000;
    private int mCoordinateType = LBSTraceClient.TYPE_AMAP;
    private List<TraceLocation> mTraceList; //线路的集合
    private ConcurrentMap<Integer, TraceOverlay> mOverlayList = new ConcurrentHashMap<Integer, TraceOverlay>();
    //自定义的infoWindow
    private View infoWindow = null;
    //请求presenter
    private TramcarContract.Presenter presenter;
    //所有站点坐标点集合
    private List<LatLng> latLngs;
    //所有站点距离你集合
    private List<StopsDistance> stopsDistanceList = new ArrayList<>();
    //线路查看中fragment集合
    private List<Fragment> mFragmentList = new ArrayList<>();
    private RouteFragmentPagerAdapter pagerAdapter;

    //路径规划
    RouteSearch mRouteSearch;

    Marker mNowShowInfoWindowMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tramcar);
        tramcar_map = (MapView) findViewById(R.id.tramcar_map);
        tramcar_map.onCreate(savedInstanceState);// 此方法必须重写
        presenter = new TramcarPresenter(this, SchedulerProvider.getInstance(), HttpService.Factory.create(Constants.BASE_URL_FOR_TAXI_ABOUT_INFO));

        initView();
        initData();
    }

    private void initData() {


        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = tramcar_map.getMap();
            mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象

            mUiSettings.setZoomControlsEnabled(false);//不显示放大缩小按钮
            mUiSettings.setCompassEnabled(true); //显示指南针
            // 设置定位监听
            aMap.setLocationSource(this);
            // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            aMap.setMyLocationEnabled(true);
            // 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种
            aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        }
        // 绑定 Marker 被点击事件
        aMap.setOnMarkerClickListener(markerClickListener);
        //设置自定义的infowindow
        aMap.setInfoWindowAdapter(this);//AMap类中
        //绑定信息窗点击事件
        aMap.setOnInfoWindowClickListener(InfoWindowlistener);
        //mTraceClient = new LBSTraceClient(this.getApplicationContext());
    }


    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        rd_title = (TextView) findViewById(R.id.rd_title);
        tv_recent_stop = (TextView) findViewById(R.id.tv_recent_stop);
        tv_route_look = (TextView) findViewById(R.id.tv_route_look);

        ly_route_search = (LinearLayout) findViewById(R.id.ly_route_search);
        rg_direction = (RadioGroup) findViewById(R.id.rg_direction);
        rb_to_nm = (RadioButton) findViewById(R.id.rb_to_nm);
        rb_to_tyc = (RadioButton) findViewById(R.id.rb_to_tyc);
        vp_routes = (ViewPager) findViewById(R.id.vp_routes);

        progDialog = new ProgressDialog(this);

        iv_back.setOnClickListener(this);
        tv_recent_stop.setOnClickListener(this);
        tv_recent_stop.setTag("notshow");
        tv_route_look.setOnClickListener(this);
        tv_route_look.setTag("notshow");
        vp_routes.addOnPageChangeListener(this);
        rg_direction.setOnCheckedChangeListener(this);
        //设置fragments
        ToNmFragment toNmFragment = ToNmFragment.newInstance(null);
        ToTygFragment toTygFragment = ToTygFragment.newInstance(null);

        mFragmentList.add(toNmFragment);
        mFragmentList.add(toTygFragment);
        pagerAdapter = new RouteFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
        vp_routes.setAdapter(pagerAdapter);
        //vp_routes.setOffscreenPageLimit(2); //来回切换不重新加载
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            finish();
        }
        //最近车站
        if (v.getId() == R.id.tv_recent_stop) {
            if (((String) tv_recent_stop.getTag()).equals("notshow")) {
                tv_recent_stop.setTextColor(getResources().getColor(R.color.yellow));
                tv_recent_stop.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_rent_stop_yellow), null, null, null);
                tv_recent_stop.setTag("show");

                ly_route_search.setVisibility(View.GONE);
                tramcar_map.setVisibility(View.VISIBLE);
                presenter.getRecentStop(latitude + "", longtitude + "");

                tv_route_look.setTextColor(getResources().getColor(R.color.white));
                tv_route_look.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_route_look), null, null, null);
                tv_route_look.setTag("notshow");

            } else if (((String) tv_recent_stop.getTag()).equals("show")) {
                tv_recent_stop.setTextColor(getResources().getColor(R.color.white));
                tv_recent_stop.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_rent_stop), null, null, null);
                tv_recent_stop.setTag("notshow");

                //清除路线
                if (mAllWalkRouteOverlayList.size() > 0) {
                    for (int i = 0; i < mAllWalkRouteOverlayList.size(); i++) {
                        mAllWalkRouteOverlayList.get(i).removeFromMap();
                    }
                    mAllWalkRouteOverlayList.clear();
                }
                //隐藏marker的infoWindow
                mNowShowInfoWindowMarker.hideInfoWindow();


                tv_route_look.setTextColor(getResources().getColor(R.color.white));
                tv_route_look.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_route_look), null, null, null);
                tv_route_look.setTag("notshow");
            }
        }

        //线路查看
        if (v.getId() == R.id.tv_route_look) {
            if (((String) tv_route_look.getTag()).equals("notshow")) {

                ly_route_search.setVisibility(View.VISIBLE);
                tv_recent_stop.setTextColor(getResources().getColor(R.color.white));
                tv_route_look.setTextColor(getResources().getColor(R.color.yellow));

                tv_recent_stop.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_rent_stop), null, null, null);
                tv_route_look.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_route_look_yellow), null, null, null);


                tv_route_look.setTag("show");

                if (((String) tv_recent_stop.getTag()).equals("show")) {
                    //清除路线
                    if (mAllWalkRouteOverlayList.size() > 0) {
                        for (int i = 0; i < mAllWalkRouteOverlayList.size(); i++) {
                            mAllWalkRouteOverlayList.get(i).removeFromMap();
                        }
                        mAllWalkRouteOverlayList.clear();
                    }
                    //隐藏marker的infoWindow
                    mNowShowInfoWindowMarker.hideInfoWindow();
                }

                tv_recent_stop.setTag("notshow");


            } else if (((String) tv_route_look.getTag()).equals("show")) {
                ly_route_search.setVisibility(View.GONE);
                tv_recent_stop.setTextColor(getResources().getColor(R.color.white));
                tv_route_look.setTextColor(getResources().getColor(R.color.white));
                tv_recent_stop.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_rent_stop), null, null, null);
                tv_route_look.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_route_look), null, null, null);


                tv_route_look.setTag("notshow");
                tv_recent_stop.setTag("notshow");
            }


            //会引起闪屏
            //tramcar_map.setVisibility(View.INVISIBLE);
        }
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mOnLocationChangeListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //获取一次定位结果：
            mLocationOption.setOnceLocationLatest(true);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {

        mOnLocationChangeListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {

        if (mOnLocationChangeListener != null && amapLocation != null) {
            if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                mOnLocationChangeListener.onLocationChanged(amapLocation);// 显示系统小蓝点

                longtitude = amapLocation.getLongitude();
                latitude = amapLocation.getLatitude();
                userLatLonPoint = new LatLonPoint(latitude, longtitude);
                //设置显示级别
                aMap.moveCamera(CameraUpdateFactory.zoomTo(14));


                //发起请求，获取所有站点距离
                presenter.getAllDistance(latitude + "", longtitude + "");
                //***发出请求获取数据
                //presenter.getTramcarStops();

            } else {
                String errText = "定位失败,将定位到市中心" + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                presenter.getAllDistance(Session.specialLat + "", Session.specialLon + "");
                Log.e("AmapErr", errText);
            }

        }
    }

    //展示数据，并添加站点路线标记
    @Override
    public void showTramcarStops(List<Tramcar> tramcarList) {

        mTramcarList.addAll(tramcarList);
        //绘制marker
        /*Marker marker = aMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title("站点")
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(), R.drawable.redstop)))
                .draggable(true));*/

        mTraceList = new ArrayList<TraceLocation>();
        latLngs = new ArrayList<LatLng>();
        for (int i = 0; i < tramcarList.size(); i++) {
            double latitude = Double.parseDouble(tramcarList.get(i).getLatitude());
            double longtitude = Double.parseDouble(tramcarList.get(i).getLongitude());
            String stopName = tramcarList.get(i).getStation_name();
            LatLng latLng = new LatLng(latitude, longtitude);
            latLngs.add(latLng);

            String distance = stopsDistanceList.get(i).getDistance(); //distance + "m"
            //绘制标记点marker
            /*mLocMarker = aMap.addMarker(new MarkerOptions().position(latLng).title(stopName).snippet(String.valueOf(i+1))
                    );*/

            Marker newMarker = aMap.addMarker(new MarkerOptions()
                    .position(latLng).icon(BitmapDescriptorFactory.
                            fromView(getMarkerView(String.valueOf(i + 1)))).title(stopName).snippet(distance + "m"));
            mMarkerList.add(newMarker);
                    /*.icon(BitmapDescriptorFactory.fromBitmap(getMyBitmap(pm.getPm()+""))));
            localMarker.setObject(pm);*/


            /*.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(), R.drawable.bluestop)));*/
            TraceLocation traceLocation = new TraceLocation();
            traceLocation.setLatitude(latitude);
            traceLocation.setLongitude(longtitude);
            mTraceList.add(traceLocation);
        }
        //绘制曲线
        aMap.addPolyline((new PolylineOptions())
                .addAll(latLngs)
                .width(20)
                .geodesic(true).color(getResources().getColor(R.color.blue)));

        //下面是发起轨迹纠偏
        traceGrasp();
    }

    @Override
    public void showGetTramcarStopsError(String tip) {

    }


    protected View getMarkerView(String pm_val) {
        View view = getLayoutInflater().inflate(R.layout.view_custom_marker, null);
        TextView tv_val = (TextView) view.findViewById(R.id.tv_marker_title);
        tv_val.setText(pm_val);
        return view;
    }

    //展示距离你最近车站信息
    @Override
    public void showRecentStop(String station_name, String distance) {


        LatLonPoint recentStopLatLonPoint = null;
        for (int i = 0; i < mTramcarList.size(); i++) {
            if (mTramcarList.get(i).getStation_name().equals(station_name)) {
                double latitude = Double.parseDouble(mTramcarList.get(i).getLatitude());
                double longtitude = Double.parseDouble(mTramcarList.get(i).getLongitude());
                String stopName = mTramcarList.get(i).getStation_name();
                LatLng latLng = new LatLng(latitude, longtitude);

                recentStopLatLonPoint = new LatLonPoint(latitude, longtitude);

                mNowShowInfoWindowMarker = aMap.addMarker(new MarkerOptions()
                        .position(latLng).icon(BitmapDescriptorFactory.
                                fromView(getMarkerView(String.valueOf(i + 1)))).title(stopName).snippet(distance + "m"));
                mNowShowInfoWindowMarker.showInfoWindow();


            }
        }

        //mWalkRouteOverlay.removeFromMap();


        showUserPointToStopPointRoute(recentStopLatLonPoint);


    }

    @Override
    public void showRecentStopError(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    //显示用户点到站点的路径
    private void showUserPointToStopPointRoute(LatLonPoint stopPoint) {
        RouteSearch.FromAndTo routeFromTo = new RouteSearch.FromAndTo(userLatLonPoint, stopPoint);
        //RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(routeFromTo, RouteSearch.DrivingDefault, null, null, "");
        //mRouteSearch.calculateDriveRouteAsyn(query);

        RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(routeFromTo, RouteSearch.WalkDefault);
        mRouteSearch.calculateWalkRouteAsyn(query);
    }

    //展示所有车站距离你的信息
    @Override
    public void showAllDistance(List<StopsDistance> stopsDistances) {

        stopsDistanceList.clear();
        stopsDistanceList.addAll(stopsDistances);

        presenter.getTramcarStops();
    }

    @Override
    public void showAllDistanceError(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    //展示站点详情
    @Override
    public void showStopDetail(StopDetail stopDetail) {

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        StopDetailFragment stopDetailFragment = StopDetailFragment.newInstance(stopDetail);
        stopDetailFragment.show(ft, "StopDetailFragment");
    }

    @Override
    public void showStopDetailError(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {
        /*progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在加载...");
        progDialog.show();*/
    }

    @Override
    public void dismissLoading() {
        /*if (progDialog != null) {
            progDialog.dismiss();
        }*/
    }

    //获取数据失败情形
    @Override
    public void showError(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setPresenter(TramcarContract.Presenter presenter) {
        this.presenter = presenter;
    }


    //轨迹纠偏失败回调
    @Override
    public void onRequestFailed(int i, String s) {
        Toast.makeText(this.getApplicationContext(), s,
                Toast.LENGTH_SHORT).show();
        if (mOverlayList.containsKey(i)) {
            TraceOverlay overlay = mOverlayList.get(i);
            overlay.setTraceStatus(TraceOverlay.TRACE_STATUS_FAILURE);
        }
    }

    //轨迹纠偏过程回调
    @Override
    public void onTraceProcessing(int i, int i1, List<LatLng> list) {
        if (list == null) {
            return;
        }
        if (mOverlayList.containsKey(i)) {
            TraceOverlay overlay = mOverlayList.get(i);
            overlay.setTraceStatus(TraceOverlay.TRACE_STATUS_PROCESSING);
            overlay.add(list);
        }
    }

    //轨迹纠偏结束回调。
    //int lineID, List<LatLng> linepoints, int distance,int watingtime
    @Override
    public void onFinished(int i, List<LatLng> list, int i1, int i2) {

        Log.e("就偏后数目", list.size() + "");
        /*if (mOverlayList.containsKey(i)) {
            TraceOverlay overlay = mOverlayList.get(i);
            overlay.setTraceStatus(TraceOverlay.TRACE_STATUS_FINISH);
            overlay.setDistance(i1);
            overlay.setWaitTime(i2);
            setDistanceWaitInfo(overlay);
        }*/

        /*aMap.addPolyline((new PolylineOptions())
                .addAll(list)
                .geodesic(true).color(Color.RED));*/

    }

    /**
     * 调起一次轨迹纠偏
     */
    private void traceGrasp() {
        if (mOverlayList.containsKey(mSequenceLineID)) {
            TraceOverlay overlay = mOverlayList.get(mSequenceLineID);
            overlay.zoopToSpan();
            int status = overlay.getTraceStatus();
            String tipString = "";
            if (status == TraceOverlay.TRACE_STATUS_PROCESSING) {
                tipString = "该线路轨迹纠偏进行中...";
            } else if (status == TraceOverlay.TRACE_STATUS_FINISH) {
                tipString = "该线路轨迹已完成";
            } else if (status == TraceOverlay.TRACE_STATUS_FAILURE) {
                tipString = "该线路轨迹失败";
            } else if (status == TraceOverlay.TRACE_STATUS_PREPARE) {
                tipString = "该线路轨迹纠偏已经开始";
            }
            Toast.makeText(this.getApplicationContext(), tipString,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        TraceOverlay mTraceOverlay = new TraceOverlay(aMap);
        mOverlayList.put(mSequenceLineID, mTraceOverlay);
        List<LatLng> mapList = traceLocationToMap(mTraceList);
        mTraceOverlay.setProperCamera(mapList);

        //轨迹纠偏暂时没效果
        /*mTraceClient = new LBSTraceClient(this.getApplicationContext());
        Log.e("mTraceList的大小2", mTraceList.size() + "");
        mTraceClient.queryProcessedTrace(mSequenceLineID, mTraceList,
                mCoordinateType, this);*/
    }

    /**
     * 轨迹纠偏点转换为地图LatLng
     *
     * @param traceLocationList
     * @return
     */
    public List<LatLng> traceLocationToMap(List<TraceLocation> traceLocationList) {
        List<LatLng> mapList = new ArrayList<LatLng>();
        for (TraceLocation location : traceLocationList) {
            LatLng latlng = new LatLng(location.getLatitude(),
                    location.getLongitude());
            mapList.add(latlng);
        }
        return mapList;
    }

    //监听自定义infowindow窗口的infowindow事件回调
    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(this).inflate(R.layout.tramcar_infowindow, null);
        }
        render(marker, infoWindow);
        return infoWindow;
    }

    // 监听自定义infowindow窗口的infocontents事件回调
    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        //如果想修改自定义Infow中内容，请通过view找到它并修改
        TextView tv_StopName = (TextView) view.findViewById(R.id.tv_stop_name);
        TextView tv_Distance = (TextView) view.findViewById(R.id.tv_distance);
        tv_StopName.setText(marker.getTitle());
        tv_Distance.setText("距离:" + marker.getSnippet());

    }

    //InfoWindow 点击事件
    AMap.OnInfoWindowClickListener InfoWindowlistener = new AMap.OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker arg0) {
            String station_name = arg0.getTitle();

            presenter.getStopDetail(station_name);
           /* FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            String station_name = arg0.getTitle();
            StopDetailFragment stopDetailFragment = StopDetailFragment.newInstance(station_name);
            stopDetailFragment.show(ft, "StopDetailFragment");*/
        }
    };

    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
        // marker 对象被点击时回调的接口
        // 返回 true 则表示接口已响应事件，否则返回false
        @Override
        public boolean onMarkerClick(Marker marker) {

            /*for (int i =0;i<mAllWalkRouteOverlayList.size();i++)
            {
                mAllWalkRouteOverlayList.get(i).removeFromMap();
            }

            mAllWalkRouteOverlayList.clear();*/

            mNowShowInfoWindowMarker = marker;

            tv_recent_stop.setTextColor(getResources().getColor(R.color.white));
            tv_route_look.setTextColor(getResources().getColor(R.color.white));
            tv_recent_stop.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_rent_stop), null, null, null);
            tv_route_look.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_route_look), null, null, null);


            LatLonPoint stopPoint = new LatLonPoint(marker.getPosition().latitude, marker.getPosition().longitude);
            showUserPointToStopPointRoute(stopPoint);
            //mWalkRouteOverlay.removeFromMap();
            /*LatLonPoint stopPoint = new LatLonPoint(marker.getPosition().latitude,marker.getPosition().longitude);
            showUserPointToStopPointRoute(stopPoint);*/
            Log.e("数据", marker.getTitle());
            return false;
        }
    };

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                rb_to_nm.setChecked(true);
                break;
            case 1:
                rb_to_tyc.setChecked(true);
                break;

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

       /* switch (checkedId) {
            case R.id.rb_to_nm:
                vp_routes.setCurrentItem(0);
                break;
            case R.id.rb_to_tyc:
                vp_routes.setCurrentItem(1);
                break;

        }*/
        if (checkedId == R.id.rb_to_nm) {
            vp_routes.setCurrentItem(0);
        }
        if (checkedId == R.id.rb_to_tyc) {
            vp_routes.setCurrentItem(1);
        }
    }


    /************
     * 生命周期相关
     *********/
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行tramcar_map.onDestroy()，销毁地图
        tramcar_map.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行tramcar_map.onResume ()，重新绘制加载地图
        tramcar_map.onResume();
        //检查网络
        settingCheck();
    }

    private void settingCheck() {
        if (!NetworkSetting.isNetworkActive(this)) {
            NetworkSetting.openSetting(this);
            return;
        }
        NetworkSetting.checkNeworkOver();
        if (GpsworkSetting.checkSetting(this)) {
            // startService(new Intent(Session.GPS_SERVICE));
            return;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行tramcar_map.onPause ()，暂停地图的绘制
        tramcar_map.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行tramcar_map.onSaveInstanceState (outState)，保存地图当前的状态
        tramcar_map.onSaveInstanceState(outState);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }


    DrivingRouteOverlay mDrivingRouteOverlay;

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int errorCode) {
        //aMap.clear();// 清理地图上的所有覆盖物
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                if (driveRouteResult.getPaths().size() > 0) {
                    mDrivingRouteOverlay.removeFromMap();
                    final DrivePath drivePath = driveRouteResult.getPaths()
                            .get(0);
                    mDrivingRouteOverlay = new DrivingRouteOverlay(
                            TramcarActivity.this, aMap, drivePath,
                            driveRouteResult.getStartPos(),
                            driveRouteResult.getTargetPos(), null);
                    mDrivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                    mDrivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                    mDrivingRouteOverlay.removeFromMap();
                    mDrivingRouteOverlay.addToMap();
                    mDrivingRouteOverlay.zoomToSpan();

                   /* int taxiCost = (int) driveRouteResult.getTaxiCost();
                    mRouteDetailDes.setText("打车约"+taxiCost+"元");
                    mBottomLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(mContext,
                                    DriveRouteDetailActivity.class);
                            intent.putExtra("drive_path", drivePath);
                            intent.putExtra("drive_result",
                                    mDriveRouteResult);
                            startActivity(intent);
                        }
                    });*/

                } else if (driveRouteResult != null && driveRouteResult.getPaths() == null) {
                    ToastUtil.showShort(TramcarActivity.this, R.string.no_result);
                }

            } else {
                ToastUtil.showShort(TramcarActivity.this, R.string.no_result);
            }
        } else {
            ToastUtil.showShort(this.getApplicationContext(), errorCode);
        }
    }


    List<WalkRouteOverlay> mAllWalkRouteOverlayList = new ArrayList<>();
    WalkRouteResult mWalkRouteResult;

    //WalkRouteOverlay mWalkRouteOverlay;
    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    //mWalkRouteOverlay.removeFromMap();


                    mWalkRouteResult = result;
                    final WalkPath walkPath = mWalkRouteResult.getPaths()
                            .get(0);
                    WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(
                            this, aMap, walkPath,
                            mWalkRouteResult.getStartPos(),
                            mWalkRouteResult.getTargetPos());
                    if (mAllWalkRouteOverlayList.size() > 0) {
                        for (int i = 0; i < mAllWalkRouteOverlayList.size(); i++) {
                            mAllWalkRouteOverlayList.get(i).removeFromMap();
                        }
                        mAllWalkRouteOverlayList.clear();
                    }


                    mAllWalkRouteOverlayList.add(walkRouteOverlay);
                    mAllWalkRouteOverlayList.get(0).addToMap();
                    mAllWalkRouteOverlayList.get(0).zoomToSpan();
                    /*for (int i=0;i<mAllWalkRouteOverlayList.size();i++)
                    {

                    }*/


                    /*mWalkRouteOverlay.removeFromMap();
                    mWalkRouteOverlay.addToMap();
                    mWalkRouteOverlay.zoomToSpan();*/

                    /*mBottomLayout.setVisibility(View.VISIBLE);
                    int dis = (int) walkPath.getDistance();
                    int dur = (int) walkPath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur)+"("+AMapUtil.getFriendlyLength(dis)+")";
                    mRotueTimeDes.setText(des);
                    mRouteDetailDes.setVisibility(View.GONE);
                    mBottomLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(mContext,
                                    WalkRouteDetailActivity.class);
                            intent.putExtra("walk_path", walkPath);
                            intent.putExtra("walk_result",
                                    mWalkRouteResult);
                            startActivity(intent);
                        }
                    });*/
                } else if (result != null && result.getPaths() == null) {
                    ToastUtil.showShort(TramcarActivity.this, R.string.no_result);
                }
            } else {
                ToastUtil.showShort(TramcarActivity.this, R.string.no_result);
            }
        } else {
            ToastUtil.showShort(TramcarActivity.this.getApplicationContext(), errorCode);
        }
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }
}
